package com.egg.facepay;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.wxpayface.IWxPayfaceCallback;
import com.tencent.wxpayface.WxPayFace;
import com.tencent.wxpayface.WxfacePayCommonCode;
import com.tencent.wxpayface.WxfacePayLoadingDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class IFSMainActivity extends Activity implements View.OnClickListener {

    public static final String TAG = "IFSMainActivity";

    private class AuthInfo {
        public String authinfo;
        public long expire_time = 0;
    }

    private AuthInfo authinfo;

    private LinearLayout mPayLayout;
    private TextView mResultTxt;
    private Button mInitBtn;
    private Button mRawBtn;
    private Button mCodeBtn;
    private Button mReportBtn;
    private EditText mMemberEdit;
    private Button mReleaseBtn;

    private static final String PARAMS_FACE_AUTHTYPE = "face_authtype";
    private static final String PARAMS_APPID = "appid";
    private static final String PARAMS_MCH_ID = "mch_id";
    private static final String PARAMS_STORE_ID = "store_id";
    private static final String PARAMS_AUTHINFO = "authinfo";
    private static final String PARAMS_OUT_TRADE_NO = "out_trade_no";
    private static final String PARAMS_TOTAL_FEE = "total_fee";
    private static final String PARAMS_TELEPHONE = "telephone";

    private static final String PARAMS_REPORT_TYPE = "type";
    private static final String PARAMS_REPORT_COST = "cost";

    private EditText mFaceMarginTop;
    private EditText mFaceNormalCount;
    private EditText mFaceCenterNum;
    private EditText mFaceThesholdPU;
    private EditText mFaceThesholdPD;
    private EditText mFaceThesholdY;
    private EditText mFaceThesholdR;
    private EditText mFaceSizeBig;
    private EditText mFaceSizeSmall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_sign);

        Log.d(TAG, "onCreate");

        mInitBtn = (Button) findViewById(R.id.init);
        mRawBtn = (Button) findViewById(R.id.raw);
        mCodeBtn = (Button) findViewById(R.id.code);
        mReportBtn = (Button) findViewById(R.id.report);
        mReleaseBtn = (Button) findViewById(R.id.release);
        mMemberEdit = (EditText) findViewById(R.id.val_mem_txt);
        mPayLayout = (LinearLayout) findViewById(R.id.pay_page);
        mResultTxt = (TextView) findViewById(R.id.pay_result);

        mFaceMarginTop = (EditText) findViewById(R.id.val_margin_top);
        mFaceNormalCount = (EditText) findViewById(R.id.val_face_normal_count);
        mFaceCenterNum = (EditText) findViewById(R.id.val_face_center_num);
        mFaceThesholdPU = (EditText) findViewById(R.id.val_thresshold_pu);
        mFaceThesholdPD = (EditText) findViewById(R.id.val_thresshold_pd);
        mFaceThesholdY = (EditText) findViewById(R.id.val_thresshold_y);
        mFaceThesholdR = (EditText) findViewById(R.id.val_thresshold_r);
        mFaceSizeBig = (EditText) findViewById(R.id.face_size_big);
        mFaceSizeSmall = (EditText) findViewById(R.id.face_size_small);


        mInitBtn.setOnClickListener(this);
        mRawBtn.setOnClickListener(this);
        mCodeBtn.setOnClickListener(this);
        mReportBtn.setOnClickListener(this);
        mReleaseBtn.setOnClickListener(this);
        mReleaseBtn.setOnClickListener(this);

//        WxfacePayLoadingDialog dialog = new WxfacePayLoadingDialog(this);
//        dialog.show();
        authinfo = new AuthInfo();
    }

    private void getAuthInfo(String rawdata) throws IOException {
        //AuthInfo info =  new AuthInfo();
        Log.d(TAG, "enter | getAuthInfo ");

        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient client = new OkHttpClient.Builder()
                    .sslSocketFactory(sslSocketFactory)
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    })
                    .build();

            RequestBody body = RequestBody.create(null, rawdata);

            Request request = new Request.Builder()
                    .url("https://wxpay.wxutil.com/wxfacepay/api/getWxpayFaceAuthInfo.php")
                    .post(body)
                    .build();

            client.newCall(request)
                    .enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.d(TAG, "onFailure | getAuthInfo " + e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            //String responseXMLString=response.body().string();
                            try {
                                authinfo.authinfo = ReturnXMLParser.parseGetAuthInfoXML(response.body().byteStream());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            Log.d(TAG, "onResponse | getAuthInfo " + authinfo.authinfo);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.init:
                Log.d(TAG, "onClick | init ");

                /* 代理功能示例

                //HashMap map = new HashMap();
                //map.put("port","8888");
                //map.put("ip","10.43.80.163");
                //服务调用
                //WxPayFace.getInstance().initWxpayface(this, map,new IWxPayfaceCallback(){
                */

                WxPayFace.getInstance().initWxpayface(this, new IWxPayfaceCallback() {
                    @Override
                    public void response(Map info) throws RemoteException {
                        Log.d(TAG, "response | initWxpayface " + info.get("return_msg"));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(IFSMainActivity.this, "初始化完成", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
                break;
            case R.id.raw:
                Log.d(TAG, "onClick | raw ");
                //print serialno before call
                Toast.makeText(IFSMainActivity.this, "serial.no: " + Build.SERIAL, Toast.LENGTH_LONG).show();
                WxPayFace.getInstance().getWxpayfaceRawdata(new IWxPayfaceCallback() {
                    @Override
                    public void response(Map info) throws RemoteException {
                        Log.d(TAG, "response | getWxpayfaceRawdata " + info.get("rawdata"));
                        String rawdata = info.get("rawdata").toString();
                        try {
                            writeFileToSDCard(info.get("rawdata").toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(IFSMainActivity.this, "获取rawdata成功，开始请求authinfo", Toast.LENGTH_SHORT).show();
                            }
                        });

                        try {
                            getAuthInfo(rawdata);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(IFSMainActivity.this, "authinfo请求已发", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
                break;
            case R.id.code:
                Log.d(TAG, "onClick | code ");
                HashMap params = new HashMap();
                params.put(PARAMS_FACE_AUTHTYPE, "FACEPAY");
                params.put(PARAMS_APPID, "10086");
                params.put(PARAMS_MCH_ID, "12306");
                params.put(PARAMS_STORE_ID, "12345");
                params.put(PARAMS_OUT_TRADE_NO, "" + (System.currentTimeMillis() / 100000));
                params.put(PARAMS_TOTAL_FEE, "22222");
                String phone = mMemberEdit.getText().toString();
                params.put(PARAMS_TELEPHONE, phone);

                //未获取rawdata的话不继续
                if(authinfo.authinfo==null){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(IFSMainActivity.this, "请先获取rawdata", Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
                }
                params.put(PARAMS_AUTHINFO, authinfo.authinfo);

                WxPayFace.getInstance().getWxpayfaceCode(params, new IWxPayfaceCallback() {
                    @Override
                    public void response(Map info) throws RemoteException {
                        final String code = info.get("return_code").toString();
                        Log.d(TAG, "response | getWxpayfaceCode " + info);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                mPayLayout.setVisibility(View.GONE);
                                mResultTxt.setVisibility(View.VISIBLE);

                                if (TextUtils.equals(code, WxfacePayCommonCode.VAL_RSP_PARAMS_SUCCESS)) {

                                    mResultTxt.setText("支付完成");

                                    try {
                                        Thread.sleep(2000);
                                    } catch (Exception e) {

                                    }

                                    WxPayFace.getInstance().updateWxpayfacePayResult(new HashMap(), new IWxPayfaceCallback() {
                                        @Override
                                        public void response(Map info) throws RemoteException {
                                            Log.d(TAG, "response: "+info.toString());

                                        }
                                    });


                                } else if (TextUtils.equals(code, WxfacePayCommonCode.VAL_RSP_PARAMS_USER_CANCEL)) {
                                    mResultTxt.setText("用户取消");

                                } else if (TextUtils.equals(code, WxfacePayCommonCode.VAL_RSP_PARAMS_SCAN_PAYMENT)) {
                                    mResultTxt.setText("扫码支付");

                                }


                                mResultTxt.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        mPayLayout.setVisibility(View.VISIBLE);
                                        mResultTxt.setVisibility(View.GONE);
                                    }
                                });


                            }
                        });

                    }
                });
                break;
            case R.id.report:
                Log.d(TAG, "onClick | report ");
                Map info = new HashMap();
                info.put(PARAMS_REPORT_TYPE, "PAY");
                info.put(PARAMS_REPORT_COST, 100);
//                WxPayFace.getInstance().report(info);
                break;

            case R.id.release:
                Log.d(TAG, "onClick | release ");
                WxPayFace.getInstance().releaseWxpayface(this);
                break;

        }
    }

    private Map initDebugMap() {

        Map info = new HashMap();
        info.put("val_margin_top", mFaceMarginTop.getText());
        info.put("val_face_normal_count", mFaceNormalCount.getText());
        info.put("val_face_center_num", mFaceCenterNum.getText());
        info.put("val_thresshold_pu", mFaceThesholdPU.getText());
        info.put("val_thresshold_pd", mFaceThesholdPD.getText());
        info.put("val_thresshold_y", mFaceThesholdY.getText());
        info.put("val_thresshold_r", mFaceThesholdR.getText());
        info.put("face_size_big", mFaceSizeBig.getText());
        info.put("face_size_small", mFaceSizeSmall.getText());
        return info;
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        WxPayFace.getInstance().releaseWxpayface(this);
        super.onDestroy();
    }

    // 写一个文件到SDCard
    private void writeFileToSDCard(String data) throws IOException {
        // 比如可以将一个文件作为普通的文档存储，那么先获取系统默认的文档存放根目录
        File parent_path = Environment.getExternalStorageDirectory();

        // 可以建立一个子目录专门存放自己专属文件
        final File file = new File(parent_path, "rawdata.txt");

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(IFSMainActivity.this, "文件路径:" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
            }
        });

        // 创建这个文件，如果不存在
        file.createNewFile();

        FileOutputStream fos = new FileOutputStream(file);

        byte[] buffer = data.getBytes();

        // 开始写入数据到这个文件。
        fos.write(buffer, 0, buffer.length);
        fos.flush();
        fos.close();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(IFSMainActivity.this, "写成文件成功", Toast.LENGTH_LONG).show();
            }
        });

    }
}